<?php
namespace app\shop\model;
use app\BaseModel;
use think\facade\Db;



class BargainAtv extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_shop_bargain_atv';


    protected $append = [

        'spe',

        'atv_status'

    ];

    /**
     * @author chenniang
     * @DataTime: 2021-01-22 18:28
     * @功能说明:活动状态
     */
    public function getAtvStatusAttr($value,$data){

        if(!empty($data['start_time'])&&!empty($data['end_time'])){

            $status = 2;

            if($data['start_time']>time()){

                $status = 1;
            }

            if($data['end_time']<time()){

                $status = 3;
            }

            return $status;
        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-20 14:24
     * @功能说明:
     */
    public function getSpeAttr($value,$data){

        if(!empty($data['id'])&&!empty($data['goods_id'])){

            $atv_spe_model = new BargainAtvSpe();

            $list = $atv_spe_model->dataSelect($data['id'],$data['goods_id']);
            //总库存
            $all_stock = array_sum(array_column($list,'true_stock'));

            if($all_stock<=0){

                $this->where(['id'=>$data['id'],'status'=>1])->update(['status'=>0]);
            }

            return $list;

        }

    }



    /**
     * @author chenniang
     * @DataTime: 2020-12-09 14:17
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-09 14:18
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $data['update_time'] = time();

        $spe = $data['spe'];

        unset($data['spe']);

        Db::startTrans();

        $res = $this->insert($data);

        $id  = $this->getLastInsID();

        $res = $this->updateSome($id,$spe,$data['uniacid'],$data['user_num']);

        if(!empty($res['code'])){

            Db::rollback();

            return $res;
        }

        Db::commit();

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-19 10:36
     * @功能说明:编辑
     */
   public function dataUpdate($dis,$data){

       $data['update_time'] = time();

       $spe = $data['spe'];

       unset($data['spe']);

       Db::startTrans();

       $res = $this->where($dis)->update($data);

       $res = $this->updateSome($data['id'],$spe,$data['uniacid'],$data['user_num']);

       if(!empty($res['code'])){

           Db::rollback();

           return $res;
       }

       Db::commit();

       return $res;

   }

    /**
     * @author chenniang
     * @DataTime: 2021-01-19 10:46
     * @功能说明:详情
     */
   public function dataInfo($dis){

       $data = $this->where($dis)->find();

       return !empty($data)?$data->toArray():[];

   }


    /**
     * @author chenniang
     * @DataTime: 2021-01-20 14:04
     * @功能说明:添加规格
     */
   public function updateSome($id,$spe,$uniacid,$num){

       $atv_spe_model = new BargainAtvSpe();
       //先删除该活动的所有
       $atv_spe_model->where(['atv_id'=>$id])->delete();

//       $spe_model = new AdminShopSpePrice();

       foreach ($spe as $k => $value){

           $insert = [

               'uniacid'  => $uniacid,

               'atv_id'   => $id,

               'stock'    => $value['stock'],

               'low_price'=> $value['low_price'],

               'spe_id'   => $value['spe_id'],

               'goods_id' => $value['goods_id']
           ];
           //检查一下
           $check = $this->check($insert);

           if(!empty($check['code'])){

               return $check;
           }

           $init_price = Db::name('longbing_card_shop_spe_price')->where(['id'=>$value['spe_id']])->sum('price');

           $y_price = $init_price-$value['low_price'];

           if($y_price/$num<0.01){

               return ['code'=>500,'msg'=>'每人砍价最少0.01元,请核对底价和砍价人数，计算方式:（原价-底价)/砍价人数>0.01'];
           }

           $atv_spe_model->dataAdd($insert);

       }

       return true;

   }


    /**
     * @author chenniang
     * @DataTime: 2021-01-19 11:31
     * @功能说明:检查一下添加编辑的数据
     */
   public function check($data){

       $spe_model = new AdminShopSpePrice();

       $record_mdoel = new BargainRecord();

       $spe = $spe_model->where(['id'=>$data['spe_id']])->find();


       if(empty($spe)){

           return ['code'=>500,'msg'=>'该规格不存在'];
       }

       $spe = $spe->toArray();
       //判断规格库存
       if($spe['stock']<$data['stock']){

           return ['code'=>500,'msg'=>$spe['spe_name_text'].'库存需小于商品库存,商品库存'.$spe['stock']];
       }

       $dis[] = ['atv_id','=',$data['atv_id']];

       $dis[] = ['status','>=',2];

       $dis[] = ['spe_id','=',$data['spe_id']];

       $lock = $record_mdoel->where($dis)->sum('num');
       //判断规格库存
       if($lock>$data['stock']){

           return ['code'=>500,'msg'=>$spe['spe_name_text'].'库存需大于已经砍价成功数量,数量'.$lock];
       }
       //判断价格
       if($spe['price']<$data['low_price']){

           return ['code'=>500,'msg'=>$spe['spe_name_text'].'需小于商品价格,商品价格'.$spe['price']];

       }

       return true;

   }


    /**
     * @author chenniang
     * @DataTime: 2021-01-20 10:26
     * @功能说明:查询进行中的活动
     */
   public function atvIng($goods_id){

       $dis[] = ['goods_id','=',$goods_id];

       $dis[] = ['start_time','<',time()];

       $dis[] = ['end_time','>',time()];

       $dis[] = ['status','=',1];

       $data = $this->where($dis)->field('end_time,id,goods_id,name_auth,mobile_auth')->find();

       if(empty($data)){

           return [];
       }

       $data = $data->toArray();
       //如果没有规格返回空
       if(empty($data['spe'])){

           return [];
       }
       //最小价格
       $data['mini_price'] = min(array_column($data['spe'],'low_price'));
       //总库存
       $data['all_stock']  = array_sum(array_column($data['spe'],'true_stock'));

       $data['end_time']  -= time();

       return $data;

   }


    /**
     * @author chenniang
     * @DataTime: 2021-01-20 10:26
     * @功能说明:查询进行中的活动
     */
    public function atvIngList($dis,$where,$page=10){

        $data = $this->alias('e')
            ->join('longbing_card_goods a','e.goods_id = a.id')
            ->leftJoin('longbing_card_company_goods b' ,'a.id = b.goods_id')
            ->join('longbing_card_shop_bargain_atv_spe c' ,'e.id = c.atv_id')
            ->where($dis)
            ->where(function ($query) use ($where){
                $query->whereOr($where);
            })
            ->field(['a.cover,a.name,e.end_time,e.id,e.goods_id,e.name_auth,e.mobile_auth'])
            ->group('a.id')
            ->order('a.recommend desc,a.top desc,a.id desc,a.update_time desc')
            ->paginate($page)
            ->toArray();

        $data['data'] = transImages($data['data'],['cover'],',');

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){
                //最小价格
                $v['mini_price'] = min(array_column($v['spe'],'low_price'));
                //剩余总库存
                $v['all_true_stock'] = array_sum(array_column($v['spe'],'true_stock'));
                //总数量
                $v['all_stock']  = array_sum(array_column($v['spe'],'stock'));

                $v['end_time']  -= time();
            }

        }

        $data['min_price'] = $this->minPrice($dis,$where);

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-03 14:10
     * @功能说明:获取砍价活动列表页商品价格最低的价格
     */
    public function minPrice($dis,$where){

        $data = $this->alias('e')
            ->join('longbing_card_goods a','e.goods_id = a.id')
            ->leftJoin('longbing_card_company_goods b' ,'a.id = b.goods_id')
            ->join('longbing_card_shop_bargain_atv_spe c' ,'e.id = c.atv_id')
            ->where($dis)
            ->where(function ($query) use ($where){
                $query->whereOr($where);
            })
            ->min('low_price');

        return !empty($data)?$data:0;

    }

    /**
     * @author chenniang
     * @DataTime: 2021-01-22 18:16
     * @功能说明:
     */
   public function allStock(){


   }


    /**
     * @author chenniang
     * @DataTime: 2021-01-21 14:55
     * @功能说明:检查活动
     */
    public function atvCheck($atv_id){




    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-22 15:51
     * @功能说明:我正在进行中的活动
     */
    public function myRecordIng($goods_id,$user_id){

        $record_model = new BargainRecord();

        $dis = [

            'user_id' => $user_id,

            'goods_id'=> $goods_id
        ];
        //已经发起砍价的次数
        $id = $record_model->where($dis)->where('over_time','>',time())->where('status','in',[1,2])->value('id');

        return $id;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-24 16:26
     * @功能说明:获取必须
     */
    public function mastAtvSpe($goods_id){

        $dis[] = ['goods_id','=',$goods_id];

        $dis[] = ['status','=',1];

        $dis[] = ['start_time','<',time()];

        $dis[] = ['end_time','>',time()];

        $dis[] = ['buy_must','=',1];

        $data = $this->dataInfo($dis);

        $spe = [];

        if(!empty($data)){

            $spe = array_column($data['spe'],'spe_id');
        }

        return $spe;

    }





}